package message

import (
	"context"
	"github.com/star-find-cloud/star-chat/message/domain"
	"github.com/star-find-cloud/star-chat/message/pb"
	log "github.com/star-find-cloud/star-chat/pkg/logger"
	"google.golang.org/grpc"
	"io"
)

type MessageGrpcHandler struct {
	service domain.Service
}

func (m *MessageGrpcHandler) SendMsg(stream grpc.ClientStreamingServer[pb.SendRequest, pb.SendResponse]) error {
	// 循环接收数据
	for {
		// 处理单个数据
		req, err := stream.Recv()
		// 消息获取完成, 退出循环
		if err == io.EOF {
			break
		}
		if err != nil {
			log.GrpcLogger.Errorf("接收信息错误: %v", err)
			return stream.SendAndClose(&pb.SendResponse{
				Code:    500,
				Message: "接收信息错误",
			})
		}

		message := &domain.Message{
			FromID: req.GetFromId(),
			ToID:   req.GetToId(),
			Msg:    req.GetBody(),
			Type:   req.GetType(),
			Token:  req.GetToken(),
			FromIP: req.GetFromIp(),
			ToIP:   req.GetToIp(),
		}
		msgChan := make(chan *domain.Message, 10)
		msgChan <- message
		err = m.service.Send(context.Background(), msgChan)
		if err != nil {
			log.GrpcLogger.Errorf("发送信息错误: %v", err)
			return stream.SendAndClose(&pb.SendResponse{
				Code:    500,
				Message: "发送信息错误",
			})
		}
	}
	return stream.SendAndClose(&pb.SendResponse{
		Code:    200,
		Message: "发送信息成功",
	})
}

func (m *MessageGrpcHandler) FindMsgByUser(ctx context.Context, request *pb.FindMsgByUserRequest) (*pb.FindMsgByUserResponse, error) {
	//TODO implement me
	panic("implement me")
}

func (m *MessageGrpcHandler) FindMsgByText(ctx context.Context, request *pb.FindMsgByTextRequest) (*pb.FindMsgByTextResponse, error) {
	//TODO implement me
	panic("implement me")
}

func (m *MessageGrpcHandler) DeleteMsg(ctx context.Context, request *pb.DeleteMsgRequest) (*pb.DeleteMsgResponse, error) {
	//TODO implement me
	panic("implement me")
}

func (m *MessageGrpcHandler) mustEmbedUnimplementedMsgServiceServer() {
	//TODO implement me
	panic("implement me")
}
